<template>
  <div class="reserve-order">
    <van-nav-bar
      title="心理预约"
      left-text="返回"
      left-arrow
      fixed
      @click="handleBack"
    />

    <van-form ref="formRef" @submit="handleSubmit">
      <van-field
        :model-value="form.reserveDate"
        name="date"
        label="预约日期"
        readonly
      />
      <van-field
        :model-value="reserveDateRange"
        readonly
        name="grade"
        label="预约时间"
      />
      <van-field v-model="form.phone" name="phone" label="联系手机" />
      <van-field v-model="form.requirement" name="requirement" label="服务需求">
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交预约
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
import { Toast } from 'vant'
import { reactive, defineProps, toRefs, Ref, computed, watchEffect } from 'vue'
import { useReserveForm } from '../use/useReserveForm'
import { useBack } from '/@/use/useRouteBack'
import { receiveSave } from '/@/views/reserve/api'

type PropsType = { id: string; tenantId: string }

const props = defineProps<PropsType>()

const { id, tenantId } = toRefs(props)

const { back: handleBack } = useBack()

const { form, reserveDateRange, handleSubmit } = useForm(id, tenantId)

function useForm(id: Ref<string>, tenantId: Ref<string>) {
  const { form: reserveForm } = useReserveForm(id, tenantId)
  const form = reactive({
    status: 1,
    appointmentPublishId: props.id,
    reserveDate: reserveForm.reserveDate,
    reserveStartTime: reserveForm.reserveStartTime,
    reserveEndTime: reserveForm.reserveEndTime,
    phone: '',
    requirement: '',
  })

  const { back } = useBack()

  watchEffect(() => {
    const { reserveDate, reserveStartTime, reserveEndTime } = reserveForm
    Object.assign(form, { reserveDate, reserveStartTime, reserveEndTime })
  })

  return {
    form,
    reserveDateRange: computed(
      () => `${form.reserveStartTime} ~ ${form.reserveEndTime}`
    ),
    async handleSubmit() {
      const { status, appointmentPublishId, phone, requirement } = form
      const params = {
        status,
        appointmentPublishId,
        phone,
        requirement,
        tenantId: tenantId?.value,
      }
      const { data } = await receiveSave(params)
      Toast('预约成功!').$nextTick(back)
    },
  }
}
</script>

<style lang="less" scoped>
.reserve-order {
  padding-top: 60px;
  margin-bottom: 60px;
}
</style>
